﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Collections.Generic;

namespace LinkED_WP
{
    public class LinkED_DataSource
    {
        static public LinkED_DBHelper m_LocalDataBase;
        static public AllPCListBoxPresenter m_PCResource;
        static public ushort m_port = 20000;
        static public string m_NtType = "TCP";

        static public void InitialLocalDB()
        {
            // 查询所有记录
            m_LocalDataBase = new LinkED_DBHelper(LinkED_DBHelper.DBConnectionString);
            var recorders = from LinkED_PCItem items in m_LocalDataBase.PCItemTable select items;
            m_PCResource = new AllPCListBoxPresenter();
            m_PCResource.PCItems = new ObservableCollection<LinkED_PCItem>(recorders);
        }

        static public void InsertIntoDataBase(LinkED_PCItem newPC)
        {
            // 查询所有记录
            m_LocalDataBase.PCItemTable.InsertOnSubmit(newPC);
            m_LocalDataBase.SubmitChanges();

            SyncData();

        }

        static public void DeleteByPCID(int PCID)
        {
           var target = from LinkED_PCItem items 
                        in m_LocalDataBase.PCItemTable
                        where items.PCID == PCID
                        select items;

            var pc = new ObservableCollection<LinkED_PCItem>(target).Single();

            m_LocalDataBase.PCItemTable.DeleteOnSubmit(pc);

            m_LocalDataBase.SubmitChanges();

            SyncData();
        }

        static public void EmptyLocalDB()
        {
            IEnumerable<LinkED_PCItem> allPCs = (from LinkED_PCItem items 
                  in m_LocalDataBase.PCItemTable select items).ToList();

            m_LocalDataBase.PCItemTable.DeleteAllOnSubmit(allPCs);
            m_LocalDataBase.SubmitChanges();

            m_PCResource.PCItems.Clear();
        }

        static public void SetCfgParameters(ushort port, string Nttype)
        {
            m_port = port;
            m_NtType = Nttype;
        }

        static void SyncData()
        {
            m_PCResource.PCItems.Clear();

            IEnumerable<LinkED_PCItem> allPCs = (from LinkED_PCItem items
                        in m_LocalDataBase.PCItemTable
                                                 select items).ToList();

            foreach (LinkED_PCItem itm in allPCs)
            {
                m_PCResource.PCItems.Add(itm);
            }

        }


    }
}
